<!--
 * @Author: your name
 * @Date: 2021-08-24 16:19:37
 * @LastEditTime: 2021-08-29 19:21:01
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue电商管理平台\vue-e-commerce\src\components\goods\Params.vue
-->


<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="catelist"
            :props="cascaderProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many"
          ><el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addAttrDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 数据表 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <!-- 标签 -->
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleTagClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 新标签</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only"
          ><el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addAttrDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 数据表 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <!-- 标签 -->
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleTagClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 新标签</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table></el-tab-pane
        >
      </el-tabs>
    </el-card>
    <!-- 添加 动态参数 / 静态属性 对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addAttrDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addAttrForm"
        :rules="rules"
        ref="addAttrRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addAttrForm.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAttrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑 动态参数 / 静态属性 对话框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editAttrDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editAttrForm"
        :rules="rules"
        ref="editAttrRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editAttrForm.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAttrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      catelist: [],
      // 级联选择器的配置
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //级联选择器 选中的值
      selectedKeys: [],
      // tab 激活项
      activeName: "many",
      // 动态参数 数据
      manyTableData: [],
      // 静态属性 数据
      onlyTableData: [],
      //对话框 显示/隐藏
      addAttrDialogVisible: false,
      editAttrDialogVisible: false,
      // 添加参数的表单数据
      addAttrForm: {
        attr_name: "",
      },
      // 验证规则
      rules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      //编辑参数的表单数据
      editAttrForm: {},
      // tag 标签的数据在 getParamsData 请求动态参数 / 静态属性 数据时被初始化
      //控制添加标签
      // inputVisible: false,
      //添加标签 的输入框数据
      // inputValue: "",
    };
  },
  computed: {
    //控制 添加参数/属性 按钮是否禁用
    isBtnDisabled() {
      return this.selectedKeys.length === 3 ? false : true;
    },
    // cascader 选中的三级分类 id
    cateId() {
      return this.selectedKeys.length === 3 ? this.selectedKeys[2] : null;
    },
    // 对话框 的标题文本
    titleText() {
      return this.activeName === "many" ? "动态参数" : "静态属性";
    },
  },
  methods: {
    //商品分类数据
    async getCateList() {
      const { data: res } = await this.$axios.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }
      this.catelist = res.data;
    },
    // 监听 cascader 选项变化
    handleChange() {
      this.getParamsData();
    },
    //监听 tab 激活
    handleTabClick() {
      this.getParamsData();
    },
    // 请求动态参数 / 静态属性 数据
    async getParamsData() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      //选中三级分类
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表失败");
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 初始化本行的添加新标签
        item.inputVisible = false;
        item.inputValue = "";
      });
      this.activeName === "many"
        ? (this.manyTableData = res.data)
        : (this.onlyTableData = res.data);
    },
    //监听 添加参数 对话框 关闭
    addDialogClosed() {
      this.$refs.addAttrRef.resetFields();
    },
    //添加参数
    addParams() {
      this.$refs.addAttrRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.axios.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.addAttrForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加参数失败");
        }
        this.$message.success("添加参数成功");
        this.addAttrDialogVisible = false;
        this.getParamsData();
      });
    },
    //监听 编辑 对话框 打开
    async showEditDialog(id) {
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败");
      }
      this.editAttrForm = res.data;
      this.editAttrDialogVisible = true;
    },
    //监听 编辑 对话框  关闭
    editDialogClosed() {
      this.$refs.editAttrRef.resetFields();
    },
    //编辑参数
    editParams() {
      this.$refs.editAttrRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$axios.put(
          `categories/${this.cateId}/attributes/${this.editAttrForm.attr_id}`,
          {
            attr_name: this.editAttrForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新参数失败");
        }
        this.$message.success("更新参数成功");
        this.getParamsData();
        this.editAttrDialogVisible = false;
      });
    },
    //删除参数
    async removeParams(id) {
      const confirmResult = await this.$confirm("是否删除该参数?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$axios.delete(
        `categories/${this.cateId}/attributes/${id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除参数失败");
      }
      this.$message.success("删除参数成功");
      this.getParamsData();
    },
    //切换 添加新标签 / 输入框
    showInput(row) {
      row.inputVisible = true;
      //输入框自动获得焦点
      // $nextTick 页面元素重新渲染后触发回调
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //添加新标签
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row);
    },
    //保存标签数据
    async saveAttrVals(row) {
      const { data: res } = await this.$axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("标签修改失败");
      }
      this.$message.success("标签修改成功");
    },
    //删除标签
    handleTagClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.saveAttrVals(row);
    },
  },
  created() {
    this.getCateList();
  },
};
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
  margin: 5px;
}
.button-new-tag {
  margin: 5px;
}
</style>